package com.sgb.kjwl.view.ui.activity.self.publish;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityLeaseMachineBinding;
import com.sgb.kjwl.di.self.DaggerSelfComponent;
import com.sgb.kjwl.di.self.SelfModule;
import com.sgb.jicai.entity.FilterEntity;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.link.entity.PublicTypeEntity;
import com.sgb.kjwl.model.entity.lease.PriceSetEntity;
import com.sgb.kjwl.model.entity.transport.MapLongAndLatEntity;
import com.sgb.kjwl.model.entity.user.AddMachineOutEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.model.entity.user.PublicAttrEntity;
import com.sgb.link.entity.ReturnTypeEntity;
import com.sgb.kjwl.model.entity.user.ServiceEntity;
import com.sgb.kjwl.utils.EditInputFilter;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.PickEvent;
import com.sgb.kjwl.view.event.self.MachinePublishEvent;
import com.sgb.alimaplibrary.SelectAddressActivity;
import com.sgb.kjwl.view.ui.activity.house.LeasePriceSetActivity;
import com.sgb.kjwl.view.ui.adapter.lease.PriceShowAdapter;
import com.sgb.kjwl.view.ui.adapter.self.publish.ImageAdapter;
import com.swgk.core.view.CityPickBuilder;
import com.swgk.core.view.CityPickView;
import com.sgb.kjwl.view.widget.TimeRangePopWindow4;
import com.sgb.kjwl.view.widget.house.MachineAttrView;
import com.sgb.kjwl.viewmodel.self.publish.LeaseMachineModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.dialog.CommonDialog;
import com.swgk.core.util.CheckUtils;
import com.swgk.core.util.MDateUtil;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.Serializable;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import javax.inject.Inject;

import static com.swgk.core.event.EventConstant.EVENT_PUBLISH_MACHINE_RETURN;

/**
 * 机械出租发布
 */
public class LeaseMachineActivity extends AppActivity implements ItemInputTextView.OnWholeItemClickListener {

    @Inject
    LeaseMachineModel viewModel;

    private ActivityLeaseMachineBinding binding;
    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private boolean isLoaded = false;
    private Intent intent;
    private Bundle bundle;
    private List<PickSelectEntity> serviceEntities;
    //图片上传
    private ImageAdapter adapter;
    private List<String> urls;
    private List<File> fileList;
    public int imgTotal;
    private int currentImgNum;
    private final List<String> uploadImgList = new ArrayList<>();
    private List<PickSelectEntity> driverData, invoiceData, invoiceGGData, insuranceData, transportData, priceFixdData;
    private List<PickSelectEntity> tariffData = new ArrayList<>();
    private List<PickSelectEntity> departmentData = new ArrayList<>();
    //接口机械类型数据
    private List<PublicTypeEntity<List<PublicTypeEntity>>> publicTypeEntityList;
    //获取的属性实体
    private List<FilterEntity<List<FilterEntity>>> attrList = new ArrayList<>();
    //单位列表
//    private List<DictEntity> dictEntityList;
    private List<PickSelectEntity<List<PickSelectEntity>>> timeUnitList;
    private List<PriceSetEntity> priceSetList = new ArrayList<>();//价格设置参数列表
    //选择机械类型后返回数据
    private ReturnTypeEntity returnTypeEntity;
    //一级联动数据
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntityList;
    //二级联动数据
    private List<List<AddressEntity<List<AddressEntity>>>> opt2;
    //三级联动数据
    private List<List<List<AddressEntity>>> opt3;
    private int cityPosition1;//城市一级位置标记
    private int cityPosition2;//城市二级位置标记
    private int cityPosition3;//城市三级位置标记
    private int unitPosition;//单位选择后位置标记
    private Date today;
    private final Calendar selectedDate = Calendar.getInstance();
    private String titleString;
    private boolean isUpdate = false;
    private PriceShowAdapter priceShowAdapter;
    private String updateUserNo = "";
    private boolean isApprove = false;//是否需要审批
    private String myCompanyNo;
    private String id;
    private List<PublicAttrEntity> mEditAttrlist;
    private boolean isAttrEmpty; //属性值是否为空
    private AddMachineOutEntity.LocationEntity mLocationEntity = new AddMachineOutEntity.LocationEntity();
    private double driverAge;//驾驶员年龄
    private double maxPrice;//最高会员价

    public static void start(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, LeaseMachineActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    public static void start(Context context, String id) {
        Intent intent = new Intent();
        intent.setClass(context, LeaseMachineActivity.class);
        intent.putExtra("id", id);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //设置沉浸式状态栏的上移问题
        setTileImmerse(true);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerSelfComponent.builder()
                .appComponent(appComponent)
                .selfModule(new SelfModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(LeaseMachineActivity.this, R.layout.activity_lease_machine);
        binding.setViewModel(viewModel);
        binding.topLayout.titleView.setText("机械出租发布");
//        binding.include.tvTitleLabel.setVisibility(View.GONE);
        binding.include.rlLeaseTitle.setVisibility(View.GONE);
        binding.include.tvUse.setOnClickListener(this);
        binding.topLayout.ivBack.setOnClickListener(this);
        binding.btnSubmit.setOnClickListener(this);
        binding.btnSave.setOnClickListener(this);
        binding.itemTvPhone.setInputType(InputType.TYPE_CLASS_NUMBER);
        binding.itemTvWork.setInputType(InputType.TYPE_CLASS_NUMBER);
        binding.itemTvWork.setFilters(new EditInputFilter[]{new EditInputFilter(9999, 1, 0)});
        binding.itemTvPrice.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        binding.itemTvDriverAge.setInputType(InputType.TYPE_CLASS_NUMBER);
        binding.itemTvDriverAge.setMaxSize(2);
        binding.itemTvDrivingAge.setInputType(InputType.TYPE_CLASS_NUMBER);
        binding.itemTvDrivingAge.setCheck(2, 1);
        binding.itemTvDriverAge.onTextChange(new ItemInputTextView.onTextChange() {
            @Override
            public void change(String s) {
                if (!TextUtils.isEmpty(s)) {
                    binding.itemTvDrivingAge.setEnable(true);
                }
            }
        });
        binding.itemTvDrivingAge.onTextChange(new ItemInputTextView.onTextChange() {
            @Override
            public void change(String s) {
                if (TextUtils.isEmpty(binding.itemTvDriverAge.getContent())) {
                    MToast.showToast(LeaseMachineActivity.this, "请先输入年龄");
                    if (!TextUtils.isEmpty(s)) {
                        binding.itemTvDrivingAge.setContent("");//未输入年龄 清空已经输入的驾龄
                    }
                    binding.itemTvDrivingAge.setEnable(false);
                }
            }
        });
        binding.tvNum.setFilters(new EditInputFilter[]{new EditInputFilter(9999, 1, 0)});
        binding.itemTvSl.setOnWholeItemClickListener(this);
        binding.itemMap.setOnWholeItemClickListener(this);
        binding.itemTvAttribute.setOnWholeItemClickListener(this);
        binding.itemTvType.setOnWholeItemClickListener(this);
        binding.itemTvTime.setOnWholeItemClickListener(this);
        binding.itemTvDriver.setOnWholeItemClickListener(this);
        binding.itemTvService.setOnWholeItemClickListener(this);
        binding.itemTvInvoice.setOnWholeItemClickListener(this);
        binding.itemTvInvoiceGg.setOnWholeItemClickListener(this);
        binding.itemTvServicer.setOnWholeItemClickListener(this);
        binding.itemTvInvoice.setOnWholeItemClickListener(this);
        binding.itemTvAllowTime.setOnWholeItemClickListener(this);
        binding.itemTvInsurance.setOnWholeItemClickListener(this);
        binding.itemTvTransport.setOnWholeItemClickListener(this);
        binding.itemTvPriceIsFixed.setOnWholeItemClickListener(this);
        binding.itemTvPriceSet.setOnWholeItemClickListener(this);
        binding.itemTvDepartmentName.setOnWholeItemClickListener(this);
        binding.itemTvUnit.setOnClickListener(this);
        binding.tvAdd.setOnClickListener(v -> add());
        binding.tvSub.setOnClickListener(v -> sub());
        binding.tvDriverTip.setOnClickListener(v -> showTip());

        binding.itemTvModel.onTextChange(s -> {
            setDefaultTitle();
        });
        binding.itemTvBrand.onTextChange(s -> {
            setDefaultTitle();
        });

        //binding.nS.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
//        binding.nS.setFocusable(true);
//        binding.nS.setFocusableInTouchMode(true);
//        binding.nS.setOnTouchListener((v, event) -> {
//            v.requestFocusFromTouch();
//            return false;
//        });
        initPriceAdapter();
    }

    private void setDefaultTitle() {
        if (TextUtils.isEmpty(binding.itemTvType.getContent()) ||
                (!TextUtils.isEmpty(binding.itemTvType.getContent()) && !binding.itemTvType.getContent().contains("-"))) {
            titleString = "出租 " + binding.itemTvBrand.getContent() + binding.itemTvModel.getContent();
        } else {
            titleString = "出租 " + binding.itemTvBrand.getContent()
                    + binding.itemTvModel.getContent()
                    + binding.itemTvType.getContent().substring(binding.itemTvType.getContent().indexOf("-") + 1);
        }
        binding.include.tvTitleDefault.setText(titleString);
        binding.include.rlLeaseTitle.setVisibility(View.VISIBLE);
    }

    private void initPriceAdapter() {
        priceShowAdapter = new PriceShowAdapter(this, null);
        binding.rvPrice.setLayoutManager(new LinearLayoutManager(this));
        binding.rvPrice.setAdapter(priceShowAdapter);
    }

    @Override
    protected void init() {
        urls = new ArrayList<>();
        opt2 = new ArrayList<>();
        opt3 = new ArrayList<>();
        fileList = new ArrayList<>();

        adapter = new ImageAdapter(this, null, null, 5);
        binding.recyclerView.setLayoutManager(new GridLayoutManager(LeaseMachineActivity.this, 4));
        binding.recyclerView.setAdapter(adapter);

        //是否带驾驶员（0:是;1:否）
        driverData = new ArrayList<>();
        driverData.add(new PickSelectEntity("1", "是"));
        driverData.add(new PickSelectEntity("0", "否"));
        //是否选择发票（0:是;1:否）
        invoiceData = new ArrayList<>();
        invoiceData.add(new PickSelectEntity("1", "是"));
        invoiceData.add(new PickSelectEntity("0", "否"));
        //发票类型
        invoiceGGData = new ArrayList<>();
        invoiceGGData.add(new PickSelectEntity("0", "普通发票"));
        invoiceGGData.add(new PickSelectEntity("1", "专用发票"));
        //是否提供运输
        transportData = new ArrayList<>();
        transportData.add(new PickSelectEntity("1", "提供(运输费用协商解决)"));
        transportData.add(new PickSelectEntity("2", "不提供"));
        //有无保险
        insuranceData = new ArrayList<>();
        insuranceData.add(new PickSelectEntity("1", "有"));
        insuranceData.add(new PickSelectEntity("2", "无"));
        //租赁价格类型
        priceFixdData = new ArrayList<>();
        priceFixdData.add(new PickSelectEntity("0", "一口价"));
        priceFixdData.add(new PickSelectEntity("1", "面议"));
        viewModel.addMachineOutEntity.get().setLocation(mLocationEntity);
        initDefault();
        if (getIntent() != null && !TextUtils.isEmpty(getIntent().getStringExtra("id"))) {
            id = getIntent().getStringExtra("id");
            viewModel.getMachineOutDetailModel(id);
            binding.topLayout.titleView.setText("机械出租编辑");
        }
    }

    //设置默认参数
    private void initDefault() {
        viewModel.getTimeUnitModel();
        viewModel.getLeaseRate();//税率

        updateUserNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, "");
        myCompanyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
        String myCompanyName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NAME, "");
        String contact = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.REAL_NAME, "");
        String loginPhone = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_PHONE, "");
        binding.itemTvDepartmentUnit.setContent(myCompanyName);
        binding.itemTvDepartmentPerson.setContent(contact);
        binding.itemTvPerson.setContent(contact);
        binding.itemTvPhone.setContent(loginPhone);
        Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setContacts(contact);
        Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setContactNumber(loginPhone);

        //企业用户获取申请 部门
        if (!TextUtils.isEmpty(myCompanyNo) && !"0".equals(myCompanyNo)) {
            viewModel.getDepartment();
            binding.itemTvDepartmentUnit.setVisibility(View.VISIBLE);
            binding.itemTvDepartmentName.setVisibility(View.VISIBLE);
            binding.itemTvDepartmentPerson.setVisibility(View.VISIBLE);
        }

        binding.itemTvInvoice.setContent("是");
        binding.itemTvInvoiceGg.setContent("普通发票");
        binding.itemTvDriver.setContent("是");
        binding.itemTvTransport.setContent("提供(运输费用协商解决)");
        binding.itemTvInsurance.setContent("无");
        binding.itemTvPriceIsFixed.setContent("一口价");
        Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setDriver("1");
        Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setNeedInvoice("1");
        Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setInvoiceType("0");
        Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setSupportTransport("1");
        Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setSupportInsurance("2");
        Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setNegotiable("0");
    }

    //图片单张上传
    public void uploadRefresh(String url, int type) {
        uploadImgList.add(url);
        if (currentImgNum + 1 == imgTotal) {
            uploadImgSuccess(uploadImgList, type);
        } else {
            currentImgNum++;
            viewModel.uploadMutiFileModel(adapter.getFileList().get(currentImgNum), 0, currentImgNum + 1);
        }
    }

    //图片上传成功回调
    public void uploadImgSuccess(List<String> urls, int type) {
        //拼接图片url
        List<String> urlList = new ArrayList<>();
        for (int i = 0; i < urls.size(); i++) {
            urlList.add(urls.get(i));
        }
        if (type == 0) {
            if (viewModel.addMachineOutEntity.get().getPictures() != null) {
                viewModel.addMachineOutEntity.get().getPictures().addAll(urlList);
                urlList.clear();
                urlList.addAll(viewModel.addMachineOutEntity.get().getPictures());
            }
        }
        //addDeviceEntity.setPictures(urlList);
        StringBuilder sb = new StringBuilder("");
        for (int i = 0; i < urlList.size(); i++) {
            if (i == urlList.size() - 1) {
                sb.append(urlList.get(i));
            } else {
                sb.append(urlList.get(i)).append(",");
            }
        }
        String urlStrs = sb.toString();
        Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setImgPath(urlStrs);

        //判断是新增还是编辑
        if (binding.itemTvAttribute.getContent().equals("该类型无属性")) {
            ArrayList<PublicAttrEntity> publicAttrEntities = new ArrayList<>();
            viewModel.addMachineOutEntity.get().setAttrList(publicAttrEntities);
        }

        //企业用户判断是否需要审批
        if (binding.itemTvDepartmentName.getVisibility() == View.VISIBLE && !"0".equals(viewModel.addMachineOutEntity.get().getStatus())) {
            viewModel.haveApprovalOrNot(myCompanyNo, "machineRelease ");
        } else {
            viewModel.addMachineOutEntity.get().setCreateUser(updateUserNo);//设置更新人和创建人
            viewModel.addMachineOutEntity.get().setUpdateUser(updateUserNo);
            if (!isUpdate) {
                viewModel.addMachineOutModel("");
            } else {
                viewModel.addMachineOutModel(id);
            }
        }
    }

    public void showEditView(AddMachineOutEntity addMachineOutEntity) {
        isUpdate = true;
        viewModel.addMachineOutEntity.set(addMachineOutEntity);

        if (addMachineOutEntity.getMaxPrices() != null && addMachineOutEntity.getMaxPrices().size() > 0) {
            maxPrice = addMachineOutEntity.getMaxPrices().get(0).getMaxPrice();//获取最高会员价
        }

        if (!TextUtils.isEmpty(addMachineOutEntity.getDepartmentName()) && updateUserNo.equals(addMachineOutEntity.getUpdateUser())) {
            binding.itemTvDepartmentName.setContent(addMachineOutEntity.getDepartmentName());
        } else {
            viewModel.addMachineOutEntity.get().setDepartmentNo("");
            viewModel.addMachineOutEntity.get().setDepartmentName("");
        }

        //机械类型
        if (!TextUtils.isEmpty(addMachineOutEntity.getFirstName())) {
            binding.itemTvType.setContent(addMachineOutEntity.getFirstName() + "-" + addMachineOutEntity.getSecondName());
        }

        if (!TextUtils.isEmpty(addMachineOutEntity.getBuyTime())) {
            //购机时间  此处时间戳为10位
            selectedDate.setTime(new Date(Long.parseLong(addMachineOutEntity.getBuyTime()) * 1000L));
            binding.itemTvTime.setContent(addMachineOutEntity.getBuyTime());
        }

        //是否面议
        if ("1".equals(addMachineOutEntity.getNegotiable())) {
            binding.cb.setChecked(true);
            binding.cb.setText("您已选择面议，再次点击退出面议");
            binding.itemTvPrice.setVisibility(View.GONE);
            binding.itemTvUnit.setVisibility(View.GONE);
        } else {
            binding.cb.setChecked(false);
            binding.cb.setText("面议");
            binding.itemTvPrice.setVisibility(View.VISIBLE);
            binding.itemTvUnit.setVisibility(View.VISIBLE);
        }

        if ("1".equals(addMachineOutEntity.getNeedInvoice())) {
            binding.itemTvInvoice.setContent("是");
            binding.itemTvInvoiceGg.setVisibility(View.VISIBLE);
            binding.itemTvSl.setVisibility(View.VISIBLE);
            binding.itemTvSl.setContent(addMachineOutEntity.getTariff() + "%");
            if ("0".equals(addMachineOutEntity.getInvoiceType())) {
                binding.itemTvInvoiceGg.setContent("普通发票");
            } else {
                binding.itemTvInvoiceGg.setContent("专用发票");
            }
        } else {
            binding.itemTvInvoice.setContent("否");
            binding.itemTvInvoiceGg.setVisibility(View.GONE);
            binding.itemTvSl.setVisibility(View.GONE);
        }

        if ("1".equals(addMachineOutEntity.getDriver())) {
            binding.itemTvDriver.setContent("是");
            binding.itemTvDriverAge.setVisibility(View.VISIBLE);
            binding.itemTvDrivingAge.setVisibility(View.VISIBLE);
            binding.tvDriverTip.setVisibility(View.VISIBLE);
        } else {
            binding.itemTvDriver.setContent("否");
            binding.itemTvDriverAge.setVisibility(View.GONE);
            binding.itemTvDrivingAge.setVisibility(View.GONE);
            binding.tvDriverTip.setVisibility(View.GONE);
        }

        if (addMachineOutEntity.getLocation() != null) {
            AddMachineOutEntity.LocationEntity location = addMachineOutEntity.getLocation();
            //所在地区
            binding.itemTvService.setContent(location.getProvinceName() + location.getCityName() + location.getAreaName());
            if (TextUtils.isEmpty(location.getAddress())) {
                binding.etDetailAddress.setText(location.getTaskAddr());
            } else {
                binding.etDetailAddress.setText(location.getAddress());
            }
        }

        binding.itemTvServicer.setContent(addMachineOutEntity.getCustomerServiceName());
        //价格单位
        binding.itemTvUnit.setText(addMachineOutEntity.getPriceUnitName());

        //机械属性
//        attrEntity.setNo(addMachineOutEntity.getAttrList2().get(0).getNo());
//        attrEntity.setName(addMachineOutEntity.getAttrList2().get(0).getName());
//        binding.include.tvTitleDefault.setText(addMachineOutEntity.getTitle());
        binding.include.itemTvTitleEdit.setEditContent(addMachineOutEntity.getTitle());
        if (addMachineOutEntity.getAttrList() != null) {
            //binding.itemTvAttribute.setContent("已选择");
            mEditAttrlist = addMachineOutEntity.getAttrList();
            initMachinePublistAttrData();
        }

        //图片
        if (!TextUtils.isEmpty(addMachineOutEntity.getImgPath())) {
            String imgPath = addMachineOutEntity.getImgPath();
            List<String> imgs = new ArrayList<>();
            if (imgPath.contains(",")) {
                String[] img = imgPath.split(",");
                if (img != null && img.length > 1) {
                    for (String url : img) {
                        imgs.add(url);
                    }
                }
            } else {
                imgs.add(imgPath);
            }
            adapter.setNetImgList(imgs);
        }

        //可工作时间
        if (!TextUtils.isEmpty(addMachineOutEntity.getWorkStartTime()) && !TextUtils.isEmpty(addMachineOutEntity.getWorkEndTime())) {
            binding.itemTvAllowTime.setContent(MDateUtil.getByTimestamp(Long.parseLong(addMachineOutEntity.getWorkStartTime()), MDateUtil.Format.FORMART6.name)
                    + "-" + MDateUtil.getByTimestamp(Long.parseLong(addMachineOutEntity.getWorkEndTime()), MDateUtil.Format.FORMART6.name));
        }

        //服务范围
        //binding.cfkEditServiceArea.setEditContent(viewModel.addMachineOutEntity.get().getServiceArea());
        binding.itemEtServiceArea.setContent(viewModel.addMachineOutEntity.get().getServiceArea());
        //价格说明
        binding.cfkEditPriceExplain.setEditContent(viewModel.addMachineOutEntity.get().getPriceExplain());
        //验收说明
        binding.cfkEditAccpetExplain.setEditContent(viewModel.addMachineOutEntity.get().getAccpetExplain());
        //描述
        binding.cfkEditView.setEditContent(viewModel.addMachineOutEntity.get().getRemark());
        //闲置数量
        binding.tvNum.setText(viewModel.addMachineOutEntity.get().getAsidenum());
        //工作时长
        if (!TextUtils.isEmpty(addMachineOutEntity.getWorkDuration())) {
            binding.itemTvWork.setContent(addMachineOutEntity.getWorkDuration());
        }
        //客服
        if (!TextUtils.isEmpty(addMachineOutEntity.getCustomerServiceName())) {
            binding.itemTvServicer.setContent(addMachineOutEntity.getCustomerServiceName());
        }
        //是否提供运输
        if ("1".equals(viewModel.addMachineOutEntity.get().getSupportTransport())) {
            binding.itemTvTransport.setContent("提供(运输费用协商解决)");
        } else {
            binding.itemTvTransport.setContent("不提供");
        }
        //保险
        if ("1".equals(viewModel.addMachineOutEntity.get().getSupportInsurance())) {
            binding.itemTvInsurance.setContent("有");
        } else {
            binding.itemTvInsurance.setContent("无");
        }
        //租赁价格类型
        if ("0".equals(viewModel.addMachineOutEntity.get().getNegotiable())) {
            binding.itemTvPriceIsFixed.setContent("一口价");
            binding.itemTvPriceSet.setVisibility(View.VISIBLE);
        } else {
            binding.itemTvPriceIsFixed.setContent("面议");
            binding.itemTvPriceSet.setVisibility(View.GONE);
        }
        //价格设置
        priceSetList = addMachineOutEntity.getPriceTypeList();
        checkReatePrice();
        setDefaultTitle();
    }

    public void initAttrData(List<FilterEntity<List<FilterEntity>>> list, List<PublicAttrEntity> attributesEntityList) {
        binding.mAttrView.setData(list, attributesEntityList);
        binding.mAttrView.setAttrViewCallBack(new MachineAttrView.MachineAttrViewClickCallBack() {
            @Override
            public void hideSoft() {
                setSoftWareHide();
            }
        });
    }

    public void getMachineTypeSucc(List<PublicTypeEntity<List<PublicTypeEntity>>> datas) {
        this.publicTypeEntityList = datas;
        if (intent == null) {
            intent = new Intent();
            bundle = new Bundle();
        }
        bundle.putSerializable("publicTypeEntityList", (Serializable) publicTypeEntityList);
        bundle.putInt("type", EVENT_PUBLISH_MACHINE_RETURN);
        intent.putExtras(bundle);
        PublicPublishTypeActivity.start(this, intent);
    }

    private List<FilterEntity<List<FilterEntity>>> list;
    private List<FilterEntity> attrChildList;
    private List<PublicAttrEntity> attributesEntityList;

    public void getMachineArrtSucc(List<FilterEntity<List<FilterEntity>>> list) {
        attrList.clear();
        if (list != null) {
            attrList.addAll(list);
        }
        isAttrEmpty = (list == null || list.isEmpty());
        //attributesEntityList = binding.mAttrView.getChooseAttr();
        initAttrData(attrList, mEditAttrlist);

//        Intent intent = new Intent(LeaseMachineActivity.this, PublicPublishAttributeActivity.class);
//        Bundle bundle = new Bundle();
//        bundle.putSerializable("list", (Serializable) list);
//        bundle.putSerializable("attributesEntityList", (Serializable) viewModel.addMachineOutEntity.get().getAttrList());
//        bundle.putInt("type", EVENT_PUBLISH_MACHINE_ATTR);
//        intent.putExtras(bundle);
//        startActivity(intent);
    }

    public void setTimeList(List<PickSelectEntity<List<PickSelectEntity>>> timeUnitList) {
        this.timeUnitList = timeUnitList;
    }


    //服务范围
    public void showAddressPop(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> datas) {
        this.addressEntityList = datas;
        if (isLoaded) {
            showCityPop();
        } else {
            mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        }
    }

    @SuppressWarnings("unchecked")
    public void showCityPop() {
        //条件选择器
        CityPickView cityOption = new CityPickBuilder(LeaseMachineActivity.this, (options1, options2, options3, v) -> {
            String areaName;
            if (opt3.get(options1).get(options2).get(options3) == null) {
                areaName = "";
            } else {
                areaName = opt3.get(options1).get(options2).get(options3).getName();
                cityPosition3 = options3;
                viewModel.addMachineOutEntity.get().getLocation().setAreaNo(opt3.get(options1).get(options2).get(options3).getNo());
                viewModel.addMachineOutEntity.get().getLocation().setAreaName(opt3.get(options1).get(options2).get(options3).getName());
            }
            String content = addressEntityList.get(options1).getName()
                    + opt2.get(options1).get(options2).getName()
                    + areaName;
            binding.itemTvService.setContent(content);
            binding.etDetailAddress.setText("");
            binding.etDetailAddress.setHint("请输入详细地址");
            cityPosition1 = options1;
            cityPosition2 = options2;
            viewModel.addMachineOutEntity.get().getLocation().setProvinceNo(addressEntityList.get(options1).getNo());
            viewModel.addMachineOutEntity.get().getLocation().setCityNo(opt2.get(options1).get(options2).getNo());
            viewModel.addMachineOutEntity.get().getLocation().setProvinceName(addressEntityList.get(options1).getName());
            viewModel.addMachineOutEntity.get().getLocation().setCityName(opt2.get(options1).get(options2).getName());
        }).build();
        cityOption.setPicker(addressEntityList, opt2, opt3);
        cityOption.setSelectOptions(cityPosition1, cityPosition2, cityPosition3);
        cityOption.show();
    }

    //时间选择器
    public void showTimePop() {
        TimePickerView timePicker = new TimePickerBuilder(LeaseMachineActivity.this, (date, v) -> {
            @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
            String format = sdf.format(date);
            if (today == null)
                today = new Date();
            int compareTo = today.compareTo(date);
            if (compareTo == -1) {
                MToast.showToast(LeaseMachineActivity.this, "请选择小于今天的日期");
            } else {
                try {
                    binding.itemTvTime.setContent(format);
                    selectedDate.setTime(date);
                    Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setBuyTime(format + "");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).setType(new boolean[]{true, false, false, false, false, false}).build();
        timePicker.show();
        timePicker.setDate(selectedDate);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                onBackPressed();
                break;
            case R.id.tv_use:
                binding.include.itemTvTitleEdit.setEditContent(binding.include.tvTitleDefault.getText().toString());
                break;
            case R.id.btn_save://暂存
                viewModel.addMachineOutEntity.get().setStatus("0");
                validate();
                break;
            case R.id.btn_submit:
                viewModel.addMachineOutEntity.get().setStatus("1");
                validate();
                break;
        }
    }

    private void validate() {
        if (TextUtils.isEmpty(binding.itemTvType.getContent())) {
            MToast.showToast(LeaseMachineActivity.this, "请选择机械类型");
            return;
        } else if (TextUtils.isEmpty(binding.itemTvBrand.getContent())) {
            MToast.showToast(LeaseMachineActivity.this, "请填写机械品牌");
            return;
        } else if (TextUtils.isEmpty(binding.itemTvModel.getContent())) {
            MToast.showToast(LeaseMachineActivity.this, "请填写出厂型号");
            return;
        } else if (TextUtils.isEmpty(binding.itemTvTime.getContent())) {
            MToast.showToast(LeaseMachineActivity.this, "请选择购机时间");
            return;
        } else if (!isAttrEmpty && !checkChooseAttr()) {
            return;
        }

//        else if (TextUtils.isEmpty(binding.itemTvAttribute.getContent())) {
//            MToast.showToast(LeaseMachineActivity.this, "请选择机械属性");
//            return;
//        }

        else if (adapter.getUrls().size() == 0) {
            MToast.showToast(LeaseMachineActivity.this, "请选择图片");
            return;
        } else if (TextUtils.isEmpty(binding.itemTvPerson.getContent())) {
            MToast.showToast(LeaseMachineActivity.this, "请填写联系人姓名");
            return;
        } else if (TextUtils.isEmpty(binding.itemTvPhone.getContent())) {
            MToast.showToast(LeaseMachineActivity.this, "请填写联系电话");
            return;
        } else if (!CheckUtils.isMobileNum(binding.itemTvPhone.getContent())) {
            MToast.showToast(LeaseMachineActivity.this, "请填写正确的电话号码");
            return;
        } else if (TextUtils.isEmpty(binding.itemEtServiceArea.getContent())) {
            MToast.showToast(this, "请输入机械可服务地区");
            return;
        } else if (TextUtils.isEmpty(binding.etDetailAddress.getText())) {
            MToast.showToast(this, "请填写详细地址");
            return;
        }

        if (!TextUtils.isEmpty(binding.itemTvDriverAge.getContent())) {
            String driverAgeStr = binding.itemTvDriverAge.getContent();
            driverAge = getFormatNum(driverAgeStr);
            if (driverAge < 18 || driverAge > 60) {
                MToast.showToast(this, binding.itemTvDriverAge.getHint());
                return;
            }
        }
        if (!TextUtils.isEmpty(binding.itemTvDrivingAge.getContent())) {
            String drivingAgeStr = binding.itemTvDrivingAge.getContent();
            double drivingAge = getFormatNum(drivingAgeStr);
            if (drivingAge > driverAge - 18) {
                MToast.showToast(this, "请输入不大于" + (driverAge - 18) + "的驾龄");
                return;
            }
        }

        if ("是".equals(binding.itemTvInvoice.getContent())) {
            if (TextUtils.isEmpty(binding.itemTvSl.getContent())) {
                MToast.showToast(this, "请选择税率");
                return;
            }
        }

        if (TextUtils.isEmpty(binding.tvNum.getText())) {
            MToast.showToast(this, "请输入闲置数量");
            return;
        }

        //非面议时,价格设置必填
        if ("0".equals(viewModel.addMachineOutEntity.get().getNegotiable()) && priceSetList.size() == 0) {
            MToast.showToast(this, "请设置租赁价格");
            return;
        }

        //面议时设置价格为
        if ("1".equals(viewModel.addMachineOutEntity.get().getNegotiable())) {
            viewModel.addMachineOutEntity.get().setRentalPrice("");
            viewModel.addMachineOutEntity.get().setPriceTypeList(new ArrayList<>());
        }
        String title = binding.include.itemTvTitleEdit.getEditContent().trim();
        if (TextUtils.isEmpty(title)) {
            MToast.showToast(this, "请填写租赁名称");
            return;
        } else {
            viewModel.addMachineOutEntity.get().setTitle(title);
        }

        //兼容服务端,否则服务端会报错
        if (TextUtils.isEmpty(viewModel.addMachineOutEntity.get().getDepartmentNo())) {
            Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setDepartmentNo("");
        }
        viewModel.addMachineOutEntity.get().setRepairRemake(binding.itemTvRepairRemake.getEditContent());
        viewModel.addMachineOutEntity.get().setFuelRemake(binding.itemTvFuelRemake.getEditContent());
        viewModel.addMachineOutEntity.get().setDriverAge(binding.itemTvDriverAge.getContent());
        viewModel.addMachineOutEntity.get().setDrivingAge(binding.itemTvDrivingAge.getContent());
        viewModel.addMachineOutEntity.get().setAsidenum(binding.tvNum.getText().toString());
        viewModel.addMachineOutEntity.get().setServiceArea(binding.itemEtServiceArea.getContent());
        viewModel.addMachineOutEntity.get().setPriceExplain(binding.cfkEditPriceExplain.getEditContent());
        viewModel.addMachineOutEntity.get().setAccpetExplain(binding.cfkEditAccpetExplain.getEditContent());
        viewModel.addMachineOutEntity.get().setDescribe(binding.cfkEditView.getEditContent());
        viewModel.addMachineOutEntity.get().setRemark(binding.cfkEditView.getEditContent()); //详细说明
        viewModel.addMachineOutEntity.get().setModelName(binding.itemTvModel.getContent());
        viewModel.addMachineOutEntity.get().setAttrList(binding.mAttrView.getChooseAttr());
        viewModel.addMachineOutEntity.get().setWorkDuration(binding.itemTvWork.getContent());
        viewModel.addMachineOutEntity.get().setCategoryType("1");
        if (adapter.getFileList().size() != 0) {
            currentImgNum = 0;
            uploadImgList.clear();
            imgTotal = adapter.getFileList().size();
            viewModel.uploadMutiFileModel(adapter.getFileList().get(currentImgNum), 0, currentImgNum + 1);
        } else {
            uploadImgSuccess(adapter.getUrls(), 1);
        }
    }

    private double getFormatNum(String strNum) {
        try {
            return Double.parseDouble(strNum);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return 0;
        }
    }

    public boolean checkChooseAttr() {
        List<PublicAttrEntity> chooseAttr = binding.mAttrView.getChooseAttr();
        if (chooseAttr == null || chooseAttr.size() <= 0) {
            return true;
        }
        for (int i = 0; i < chooseAttr.size(); i++) {
            if (chooseAttr.get(i) != null) {
                if ("1".equals(chooseAttr.get(i).getKey()) && TextUtils.isEmpty(chooseAttr.get(i).getAttributeVal())) {
                    MToast.showToast(this, "请选择或填写属性值");
                    return false;
                }
            }

        }
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {// 图片结果回调
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                fileList.clear();
                urls.clear();
                for (LocalMedia localMedia : selectList) {
                    File file = new File(localMedia.getRealPath());
                    fileList.add(file);
                    urls.add(localMedia.getRealPath());
                }
                adapter.setDatas(selectList, urls);
                adapter.setFileList(fileList);
            }
        }
        if (requestCode == 255) {
            if (data == null) {
                return;
            }
            double lat = data.getDoubleExtra(SelectAddressActivity.LATITUDE, 0);
            double lon = data.getDoubleExtra(SelectAddressActivity.LONGTITUDE, 0);
            String address = data.getStringExtra(SelectAddressActivity.CURRENT_POSITION);
            binding.etDetailAddress.setText(address + "");
            viewModel.addMachineOutEntity.get().getLocation().setLatitude(lat + "");
            viewModel.addMachineOutEntity.get().getLocation().setLongitude(lon + "");
            viewModel.addMachineOutEntity.get().getLocation().setAddress(address + "");
            viewModel.addMachineOutEntity.get().getLocation().setTaskAddr(address + "");
            binding.itemMap.setContent(" ");//用空格代替hint的设置
        }
        if (requestCode == 260 && data != null) {
            priceSetList = (List<PriceSetEntity>) data.getSerializableExtra("priceSetList");
            checkReatePrice();
            viewModel.addMachineOutEntity.get().setPriceTypeList(priceSetList);
        }
    }

    //计算所有选项的含税价
    private void checkReatePrice() {
        if (priceSetList == null || priceSetList.size() == 0) return;
        binding.itemTvPriceSet.setContent("已设置");
        for (PriceSetEntity entity : priceSetList) {
            entity.setDriverReatePrice(getRatePrice(entity.getDriverPrice()));
            entity.setNoDriverReatePrice(getRatePrice(entity.getNoDriverPrice()));
            entity.setRentNo(viewModel.addMachineOutEntity.get().getNo());
            if (binding.itemTvSl.getVisibility() == View.GONE) {//若为不提供发票，则清除所有含税价
                entity.setDriverReatePrice("");
                entity.setNoDriverReatePrice("");
            }
        }
        setReatePriceText();
    }


    //计算含税价
    private String getRatePrice(String price) {
        try {
            if (TextUtils.isEmpty(viewModel.addMachineOutEntity.get().getTariff())) {
                return new DecimalFormat("0.00").format(Double.parseDouble(price));
            } else {
                Double tariff = Double.parseDouble(viewModel.addMachineOutEntity.get().getTariff());
                Double ratePrice = Double.parseDouble(price) + Double.parseDouble(price) * tariff / 100;
                return new DecimalFormat("0.00").format(ratePrice);
            }
        } catch (Exception ex) {
            return price;
        }

    }

    private void setReatePriceText() {
        if (priceSetList != null && "0".equals(viewModel.addMachineOutEntity.get().getNegotiable())) {
            boolean isDriver = "1".equals(viewModel.addMachineOutEntity.get().getDriver());
            boolean isDTariff = "1".equals(viewModel.addMachineOutEntity.get().getNeedInvoice());//有发票
            priceShowAdapter.setDriverAndTariff(isDriver, isDTariff);
            priceShowAdapter.setDatas(priceSetList);
        }
    }

    //加
    private void add() {
        if (TextUtils.isEmpty(binding.tvNum.getText().toString())) {
            return;
        }
        int num = Integer.parseInt(binding.tvNum.getText().toString());
        if (num == 9999) {//最大 9999
            return;
        }
        num += 1;
        binding.tvNum.setText(num + "");
    }

    //减
    private void sub() {
        int num = Integer.parseInt(binding.tvNum.getText().toString());
        if (num <= 1) {
            num = 1;
        } else {
            num -= 1;
        }
        binding.tvNum.setText(num + "");
    }

    private void showTip() {
        MToast.showLongToast(getActivity(), "为了安全驾驶，经营帮建议您驾驶员年龄不超过50岁", Gravity.CENTER);
    }

    @Override
    public void OnWholeItemClick(View view) {
        switch (view.getId()) {
            case R.id.item_tv_driver:
                if (null != driverData && driverData.size() > 0) {
                    OptionsPickerView businessOption = new OptionsPickerBuilder(LeaseMachineActivity.this,
                            (options1, options2, options3, v) -> {
                                String content = driverData.get(options1).getProjectscale();
                                binding.itemTvDriver.setContent(content);
                                Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setDriver(driverData.get(options1).getNo());
                                if ("否".equals(content)) {
                                    binding.itemTvDriverAge.setVisibility(View.GONE);
                                    binding.itemTvDrivingAge.setVisibility(View.GONE);
                                    binding.tvDriverTip.setVisibility(View.GONE);
                                } else {
                                    binding.itemTvDriverAge.setVisibility(View.VISIBLE);
                                    binding.itemTvDrivingAge.setVisibility(View.VISIBLE);
                                    binding.tvDriverTip.setVisibility(View.VISIBLE);
                                }
                                priceSetList.clear();
                                setReatePriceText();
                            }).build();
                    businessOption.setPicker(driverData);
                    businessOption.setSelectOptions(0);
                    businessOption.show();
                }
                break;
            case R.id.item_tv_invoice://选择发票
                if (null != invoiceData && invoiceData.size() > 0) {
                    OptionsPickerView businessOption = new OptionsPickerBuilder(LeaseMachineActivity.this,
                            (options1, options2, options3, v) -> {
                                String content = invoiceData.get(options1).getProjectscale();
                                binding.itemTvInvoice.setContent(content);
                                Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setNeedInvoice(invoiceData.get(options1).getNo());
                                if ("否".equals(content)) {
                                    binding.itemTvInvoiceGg.setVisibility(View.GONE);
                                    binding.itemTvSl.setVisibility(View.GONE);
                                    binding.itemTvSl.setContent("");//默认清空数据,重新填写
                                    viewModel.addMachineOutEntity.get().setTariff("");
                                } else {
                                    binding.itemTvInvoiceGg.setVisibility(View.VISIBLE);
                                    binding.itemTvSl.setVisibility(View.VISIBLE);
                                }
                                checkReatePrice();
                            }).build();
                    businessOption.setPicker(invoiceData);
                    businessOption.setSelectOptions(0);
                    businessOption.show();
                }
                break;
            case R.id.item_tv_invoice_gg://发票类型
                if (null != invoiceGGData && invoiceGGData.size() > 0) {
                    OptionsPickerView businessOption = new OptionsPickerBuilder(LeaseMachineActivity.this,
                            (options1, options2, options3, v) -> {
                                String content = invoiceGGData.get(options1).getProjectscale();
                                binding.itemTvInvoiceGg.setContent(content);
                                Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setInvoiceType(invoiceGGData.get(options1).getNo());
                                checkReatePrice();
                            }).build();
                    businessOption.setPicker(invoiceGGData);
                    businessOption.setSelectOptions(0);
                    businessOption.show();
                }
                break;
            case R.id.item_tv_sl://税率
                if (null != tariffData && tariffData.size() > 0) {
                    OptionsPickerView businessOption = new OptionsPickerBuilder(LeaseMachineActivity.this,
                            (options1, options2, options3, v) -> {
                                String content = tariffData.get(options1).getProjectscale();
                                binding.itemTvSl.setContent(content);
                                viewModel.addMachineOutEntity.get().setTariff(tariffData.get(options1).getNo());
                                checkReatePrice();//重新根据税率计算含税价
                            }).build();
                    businessOption.setPicker(tariffData);
                    businessOption.setSelectOptions(0);
                    businessOption.show();
                }
                break;
            case R.id.item_tv_allow_time://可工作时间
                TimeRangePopWindow4 timeRangePopWindow4 = new TimeRangePopWindow4(getActivity());
                timeRangePopWindow4.setOnTimeCallBack(new TimeRangePopWindow4.OnTimeCallBack() {

                    @Override
                    public void result(long startTime, long endTime, String content) {
                        if (startTime < endTime) {
                            binding.itemTvAllowTime.setContent(content);
                            viewModel.addMachineOutEntity.get().setWorkStartTime(String.valueOf(startTime));
                            viewModel.addMachineOutEntity.get().setWorkEndTime(String.valueOf(endTime));
                            timeRangePopWindow4.dismiss();
                        } else {
                            MToast.showToast(LeaseMachineActivity.this, "结束时间不能小于开始时间");
                        }
                    }
                });
                timeRangePopWindow4.showAtLocation(binding.mainLayout, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                break;
            case R.id.item_tv_servicer://客服
                if (this.serviceEntities == null) {
                    viewModel.getCustomerOrgDatas();
                } else {
                    if (null != serviceEntities && serviceEntities.size() > 0) {
                        OptionsPickerView businessOption = new OptionsPickerBuilder(LeaseMachineActivity.this,
                                (options1, options2, options3, v) -> {
                                    String content = serviceEntities.get(options1).getProjectscale();
                                    binding.itemTvServicer.setContent(content);
                                    Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setCustomerServiceId(serviceEntities.get(options1).getNo());
                                    Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setCustomerServiceName(serviceEntities.get(options1).getProjectscale());
                                }).build();
                        businessOption.setPicker(serviceEntities);
                        businessOption.setSelectOptions(0);
                        businessOption.show();
                    }
                }
                break;
            case R.id.item_map://详细地址地图
                if (!TextUtils.isEmpty(binding.itemTvService.getContent())) {
                    //跳转详细地址界面
                    viewModel.getLocationLL(viewModel.addMachineOutEntity.get().getLocation().getProvinceNo(),
                            viewModel.addMachineOutEntity.get().getLocation().getCityNo(), viewModel.addMachineOutEntity.get().getLocation().getAreaNo());
                } else {
                    MToast.showToast(this, "请选择所在地区");
                }
                break;
            case R.id.item_tv_type://类型
                if (publicTypeEntityList != null) {
                    if (intent == null) {
                        intent = new Intent();
                        bundle = new Bundle();
                    }
                    bundle.putSerializable("publicTypeEntityList", (Serializable) publicTypeEntityList);
                    bundle.putInt("type", EVENT_PUBLISH_MACHINE_RETURN);
                    intent.putExtras(bundle);
                    PublicPublishTypeActivity.start(this, intent);
                } else {
                    viewModel.getMachineTypeModel();
                }

                break;
//            case R.id.item_tv_attribute://属性
//                if (attrList != null) {
//                    getMachineArrtSucc(attrList);
//                } else {
//                    if (returnTypeEntity != null) {
//                        viewModel.getMachineDictModel(returnTypeEntity.getFirstNo(), returnTypeEntity.getSecondNo());
//                    } else if (viewModel.addMachineOutEntity.get() != null && !TextUtils.isEmpty(viewModel.addMachineOutEntity.get().getFirstCategory())
//                            && !TextUtils.isEmpty(viewModel.addMachineOutEntity.get().getSecondCategory())) {
//                        viewModel.getMachineDictModel(viewModel.addMachineOutEntity.get().getFirstCategory(),
//                                viewModel.addMachineOutEntity.get().getSecondCategory());
//                    } else {
//                        MToast.showToast(LeaseMachineActivity.this, "请选先选择机械类型");
//                    }
//                }
//                break;
            case R.id.item_tv_time://购机时间
                showTimePop();
                break;
            case R.id.item_tv_service://所在地区
                if (addressEntityList != null) {
                    showCityPop();
                } else {
                    viewModel.getAddressModel();
                }
                break;
            case R.id.item_tv_transport://是否提供运输
                if (null != transportData && transportData.size() > 0) {
                    OptionsPickerView businessOption = new OptionsPickerBuilder(LeaseMachineActivity.this,
                            (options1, options2, options3, v) -> {
                                String content = transportData.get(options1).getProjectscale();
                                binding.itemTvTransport.setContent(content);
                                Objects.requireNonNull(viewModel.addMachineOutEntity.get()).
                                        setSupportTransport(transportData.get(options1).getNo());

                            }).build();
                    businessOption.setPicker(transportData);
                    businessOption.setSelectOptions(0);
                    businessOption.show();
                }
                break;
            case R.id.item_tv_insurance://有无保险
                if (null != insuranceData && insuranceData.size() > 0) {
                    OptionsPickerView businessOption = new OptionsPickerBuilder(LeaseMachineActivity.this,
                            (options1, options2, options3, v) -> {
                                String content = insuranceData.get(options1).getProjectscale();
                                binding.itemTvInsurance.setContent(content);
                                Objects.requireNonNull(viewModel.addMachineOutEntity.get()).
                                        setSupportInsurance(insuranceData.get(options1).getNo());

                            }).build();
                    businessOption.setPicker(insuranceData);
                    businessOption.setSelectOptions(0);
                    businessOption.show();
                }
                break;
            case R.id.item_tv_price_is_fixed://租赁价格类型
                if (null != priceFixdData && priceFixdData.size() > 0) {
                    OptionsPickerView businessOption = new OptionsPickerBuilder(LeaseMachineActivity.this,
                            (options1, options2, options3, v) -> {
                                String content = priceFixdData.get(options1).getProjectscale();

                                if ("面议".equals(content)) {
                                    //判断是否有会员价
                                    if (viewModel.addMachineOutEntity.get().getMaxPrices() != null && viewModel.addMachineOutEntity.get().getMaxPrices().size() > 0) {
                                        MToast.showToast(LeaseMachineActivity.this, "已设置会员价的租赁商品不能再修改为面议");
                                        return;
                                    }
                                }

                                binding.itemTvPriceIsFixed.setContent(content);
                                Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setNegotiable(priceFixdData.get(options1).getNo());
                                if ("1".equals(viewModel.addMachineOutEntity.get().getNegotiable())) {
                                    binding.itemTvPriceSet.setVisibility(View.GONE);
                                    binding.rvPrice.setVisibility(View.GONE);
                                } else {
                                    binding.itemTvPriceSet.setVisibility(View.VISIBLE);
                                    binding.rvPrice.setVisibility(View.VISIBLE);
                                    setReatePriceText();
                                }
                            }).build();
                    businessOption.setPicker(priceFixdData);
                    businessOption.setSelectOptions(0);
                    businessOption.show();
                }
                break;
            case R.id.item_tv_price_set://价格设置
                if (timeUnitList == null || timeUnitList.size() == 0) {
                    MToast.showToast(LeaseMachineActivity.this, "租赁单位获取失败");
                    return;
                }
                try {
                    Intent intent = new Intent();
                    intent.putExtra("maxPrice", maxPrice);//最高会员价
                    intent.putExtra("timeUnitList", (Serializable) timeUnitList);
                    intent.putExtra("priceSetList", (Serializable) priceSetList);
                    intent.putExtra("isDriver", "1".equals(Objects.requireNonNull(viewModel.addMachineOutEntity.get()).getDriver()));
                    intent.setClass(LeaseMachineActivity.this, LeasePriceSetActivity.class);
                    startActivityForResult(intent, 260);
                } catch (Exception e) {
                    MToast.showToast(LeaseMachineActivity.this, "价格设置错误");
                }
                break;
            case R.id.item_tv_department_name://申请部门
                if (null != departmentData && departmentData.size() > 0) {
                    OptionsPickerView businessOption = new OptionsPickerBuilder(LeaseMachineActivity.this,
                            (options1, options2, options3, v) -> {
                                String content = departmentData.get(options1).getProjectscale();
                                binding.itemTvDepartmentName.setContent(content);
                                viewModel.addMachineOutEntity.get().setDepartmentNo(departmentData.get(options1).getNo());
                                viewModel.addMachineOutEntity.get().setDepartmentName(content);
                            }).build();
                    businessOption.setPicker(departmentData);
                    businessOption.setSelectOptions(0);
                    businessOption.show();
                } else {
                    MToast.showToast(LeaseMachineActivity.this, "暂无申请部门");
                }
                break;
        }
    }

    //机械类型
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReturnEvent(MachinePublishEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_PUBLISH_MACHINE_RETURN) {
            ReturnTypeEntity returnTypeEntityNow = (ReturnTypeEntity) event.getMessageData();
            if (returnTypeEntityNow.equals(returnTypeEntity)) {
                //如果选中的是之前的那个类型 什么都不做
            } else {
                returnTypeEntity = (ReturnTypeEntity) event.getMessageData();
                binding.itemTvType.setContent(returnTypeEntity.getFirstName() + "-" + returnTypeEntity.getSecondName());
                setDefaultTitle();
                Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setFirstCategory(returnTypeEntity.getFirstNo());
                Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setSecondCategory(returnTypeEntity.getSecondNo());
                Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setFirstName(returnTypeEntity.getFirstName());
                Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setSecondName(returnTypeEntity.getSecondName());
                attrList.clear();
                //binding.itemTvAttribute.setContent("");
                initMachinePublistAttrData();
            }
        }
    }

    public void initMachinePublistAttrData() {
        if (!attrList.isEmpty()) {
            getMachineArrtSucc(attrList);
        } else {
            if (returnTypeEntity != null) {
                viewModel.getMachineDictModel(returnTypeEntity.getFirstNo(), returnTypeEntity.getSecondNo());
            } else if (viewModel.addMachineOutEntity.get() != null && !TextUtils.isEmpty(viewModel.addMachineOutEntity.get().getFirstCategory())
                    && !TextUtils.isEmpty(viewModel.addMachineOutEntity.get().getSecondCategory())) {
                viewModel.getMachineDictModel(viewModel.addMachineOutEntity.get().getFirstCategory(),
                        viewModel.addMachineOutEntity.get().getSecondCategory());
            }
        }
    }

    //机械属性
    @SuppressWarnings("unchecked")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAttrEvent(PickEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_PUBLISH_MACHINE_ATTR) {
            Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setAttrList((List<PublicAttrEntity>) event.getObject());
            //binding.itemTvAttribute.setContent("已选择");
//            publicAttrEntityList = (List<PublicAttrEntity>) event.getObject();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        thread = new Thread(() -> {
                            // 子线程中解析省市区数据
                            initJsonData();
                        });
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
                    showCityPop();
                    isLoaded = true;
                    thread = null;
                    break;
                case MSG_LOAD_FAILED:
                    break;
            }
        }
    };

    private void initJsonData() {
        //城市列表
        @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") List<AddressEntity<List<AddressEntity>>> cityList;
        //区域列表
        List<List<AddressEntity>> areaList;
        for (int x = 0; x < addressEntityList.size(); x++) {
            cityList = new ArrayList<>();
            areaList = new ArrayList<>();
            if (viewModel.addMachineOutEntity.get() != null && viewModel.addMachineOutEntity.get().getProvinceNo() != null
                    && viewModel.addMachineOutEntity.get().getProvinceNo().equals(addressEntityList.get(x).getNo())) {
                cityPosition1 = x;
            }
            opt2.add(addressEntityList.get(x).getChildren());
            for (int i = 0; i < addressEntityList.get(x).getChildren().size(); i++) {
                cityList.add(addressEntityList.get(x).getChildren().get(i));
                List<AddressEntity> cityAreaList = new ArrayList<>();
                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (addressEntityList.get(x).getChildren().get(i).getChildren() == null
                        || addressEntityList.get(x).getChildren().get(i).getChildren().size() == 0) {
                    cityAreaList.add(null);
                } else {
                    cityAreaList.addAll(addressEntityList.get(x).getChildren().get(i).getChildren());
                }
                areaList.add(cityAreaList);
            }
            opt3.add(areaList);
        }
        if (viewModel.addMachineOutEntity.get() != null) {
            if (viewModel.addMachineOutEntity.get().getCityNo() != null)
                for (int x2 = 0; x2 < opt2.size(); x2++) {
                    if (viewModel.addMachineOutEntity.get().getCityNo().equals(addressEntityList.get(cityPosition1)
                            .getChildren().get(x2).getNo())) {
                        cityPosition2 = x2;
                        break;
                    }
                }
            if (viewModel.addMachineOutEntity.get().getAreaNo() != null)
                for (int x3 = 0; x3 < opt3.size(); x3++) {
                    if (viewModel.addMachineOutEntity.get().getAreaNo().equals(addressEntityList
                            .get(cityPosition1).getChildren().get(cityPosition2).getChildren().get(x3).getNo())) {
                        cityPosition3 = x3;
                        break;
                    }
                }
        }
        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }

    //税率
    public void showRate(List<PickSelectEntity> list) {
        tariffData = list;
    }

    //申请部门
    public void showDepartment(List<PickSelectEntity> list) {
        departmentData = list;
    }

    //客服
    public void getCustomerOrgDataS(List<ServiceEntity> serviceEntities) {
        this.serviceEntities = new ArrayList<>();
        for (int i = 0; i < serviceEntities.size(); i++) {
            PickSelectEntity pickSelectEntity = new PickSelectEntity();
            pickSelectEntity.setNo(serviceEntities.get(i).getId());
            pickSelectEntity.setProjectscale(serviceEntities.get(i).getName());
            this.serviceEntities.add(pickSelectEntity);
        }
        if (null != serviceEntities && serviceEntities.size() > 0) {
            OptionsPickerView businessOption = new OptionsPickerBuilder(LeaseMachineActivity.this,
                    (options1, options2, options3, v) -> {
                        String content = this.serviceEntities.get(options1).getProjectscale();
                        binding.itemTvServicer.setContent(content);
                        Objects.requireNonNull(viewModel.addMachineOutEntity.get()).
                                setCustomerServiceId(this.serviceEntities.get(options1).getNo());
                    }).build();
            businessOption.setPicker(this.serviceEntities);
            businessOption.setSelectOptions(0);
            businessOption.show();
        }
    }

    //  返回经纬度信息
    public void getLocationLL(MapLongAndLatEntity data) {
        if (!TextUtils.isEmpty(data.getLat())) {
            if (!TextUtils.isEmpty(data.getLng())) {
                Intent intent = new Intent();
                intent.setClass(this, SelectAddressActivity.class);
                intent.putExtra(SelectAddressActivity.TITLE, "详细地址");
                intent.putExtra(SelectAddressActivity.HINT, "请输入地址");
                intent.putExtra(SelectAddressActivity.SAVE_TEXT, "确定");
                intent.putExtra(SelectAddressActivity.LATITUDE, Double.parseDouble(data.getLat()));
                intent.putExtra(SelectAddressActivity.LONGTITUDE, Double.parseDouble(data.getLng()));
                startActivityForResult(intent, 255);
            }
        }
    }


    /**
     * 0.暂存:保存成功
     * 1.需要审批:提交成功(发布前提示需要审批对话框)
     * 2.不需要审批:发布成功(发布前提示不需要审批对话框)
     */
    public void showSuccess() {
        if ("0".equals(viewModel.addMachineOutEntity.get().getStatus())) {
            MToast.showToast(this, "保存成功");
        } else if (isApprove) {
            MToast.showToast(this, "提交成功");
        } else {
            MToast.showToast(this, "发布成功");
        }
    }

    /**
     * 提示审批对话框
     *
     * @param b
     */
    public void showPublishTip(boolean b) {
        isApprove = b;
        String msg = b ? "确认提交当前审批业务？" : "当前内容不需要审核，提交后即发布，确认提交？";
        new CommonDialog(getActivity()).builder().setPositiveButton("确定").setNegativeButton("取消")
                .setTitle("系统提示")
                .setMsg(msg)
                .setDialogCallBack(new CommonDialog.DialogCallBack() {
                    @Override
                    public void onRightClick() {
                        if (!isUpdate) {
                            viewModel.addMachineOutModel("");
                        } else {
                            viewModel.addMachineOutModel(id);
                        }
                    }

                    @Override
                    public void onLeftClick() {
                        return;
                    }
                }).show();
    }


    @Override
    public void onBackPressed() {
        if (TextUtils.isEmpty(id)) {
            //super.onBackPressed();
            initDialog();
            return;
        }
        finish();
    }

    public void initDialog() {
        new CommonDialog(getActivity()).builder().setPositiveButton("确定").setNegativeButton("取消")
                .setTitle("提示")
                .setMsg("你确定要返回上一步吗？返回后填写的数据将无法保存。")
                .setDialogCallBack(new CommonDialog.DialogCallBack() {
                    @Override
                    public void onRightClick() {
                        LeaseMachineActivity.this.finish();
                    }

                    @Override
                    public void onLeftClick() {
                        return;
                    }
                }).show();
    }

    ;

    /**
     * 隐藏软键盘
     */
    private void setSoftWareHide() {
        InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(this.getWindow().getDecorView().getWindowToken(), 0);
        }
    }

}

